package com.example.behaviour.webSocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.behaviour.config.SpringUtils;
import com.example.behaviour.config.WebSocketConfig;
import com.example.behaviour.mapper.ApUserMsgListMapper;
import com.example.behaviour.pojos.ApUserMsgList;
import com.example.behaviour.pojos.Message;
import com.example.common.constants.MessageConstants;
import com.example.common.redis.RedisCache;
import com.example.model.article.pojos.ApArticle;
import com.example.model.user.pojos.ApUser;
import com.example.user.mapper.ApUserMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebRTC + WebSocket
 */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{username}", configurator = WebSocketConfig.class)
public class WebSocketServer {

    /**
     * 连接集合
     */
    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username, @PathParam("publicKey") String publicKey) {
        System.out.println(username + " 开启连接了");
        sessionMap.put(username, session);
        System.out.println("sessionMap "+sessionMap.toString());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {


        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            if (entry.getValue() == session) {
                System.out.println(entry.getKey()+" 断开连接了");
                sessionMap.remove(entry.getKey());
                break;
            }
        }
    }


    private static ApUserMapper apUserMapper;


    private static ApUserMsgListMapper apUserMsgListMapper;


    private static RedisCache redisCache;

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void insertFromLatestData(RedisCache redisCache, String from, String to){
        apUserMapper = SpringUtils.getBean(ApUserMapper.class);
        apUserMsgListMapper = SpringUtils.getBean(ApUserMsgListMapper.class);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",from);
        ApUser fromUser = apUserMapper.selectOne(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name",to);
        ApUser toUser = apUserMapper.selectOne(queryWrapper1);


        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("userName",from);
        queryWrapper3.eq("friendName",to);
        ApUserMsgList apUserMsgList = apUserMsgListMapper.selectOne(queryWrapper3);
        apUserMsgList.setMsgNum(apUserMsgList.getMsgNum()+1);
        apUserMsgList.setContent("[视频通话]");
        apUserMsgListMapper.updateById(apUserMsgList);

        QueryWrapper queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("userName",toUser.getName());
        queryWrapper4.eq("friendName",fromUser.getName());
        ApUserMsgList apUserMsgList1 = apUserMsgListMapper.selectOne(queryWrapper4);
        apUserMsgList1.setMsgNum(apUserMsgList1.getMsgNum()+1);
        apUserMsgList1.setContent("[视频通话]");
        apUserMsgListMapper.updateById(apUserMsgList1);

    }



    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        redisCache = SpringUtils.getBean(RedisCache.class);
        System.out.println("sessionMap "+sessionMap.toString());
        JSONObject jsonObject = JSONObject.parseObject(message);
        String toUser = jsonObject.get("toUser").toString();
        String fromUser = jsonObject.get("fromUser").toString();
        Session toSession = sessionMap.get(toUser);
        System.out.println("收到消息 "+jsonObject.get("type")+" from "+jsonObject.get("fromUser")+" to "+jsonObject.get("toUser"));
        if("request".equals(jsonObject.get("type"))){
            System.out.println("通话请求");
            send(toSession,message);
            return;
//            Map map = JSONObject.toJavaObject(jsonObject, Map.class);
        }
        if("request_back".equals(jsonObject.get("type"))){
            System.out.println("对方接受通话请求");
            send(toSession,message);
            return;
        }
        if("leave".equals(jsonObject.get("type"))){
            insertFromLatestData(redisCache,jsonObject.get("fromUser").toString(),jsonObject.get("toUser").toString());
        }


        send(toSession,message);
    }

    /**
     * 封装一个send方法，发送消息到前端
     */
    private void send(Session session, String message) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(message);
            System.out.println("发送消息 "+jsonObject.get("type")+" from "+jsonObject.get("fromUser")+" to "+jsonObject.get("toUser"));

            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
